//
//  LZBaseViewModel.swift
//  halikaPeso
//
//  Created by L-zh on 2024/12/18.
//

import Moya
import Result
import UIKit
import MBProgressHUD
import ObjectMapper

class LZBaseViewModel: NSObject {
    // 成功回调
    public typealias succeedBlock = (_ succeed: Bool) -> Void
    open weak var viewController: LZBaseVC?
    
    open func requestWithURL(successBlock: @escaping succeedBlock) {}
    
    var isFolding: Bool? {
        didSet {
            let tableViewVc = viewController as?LZBaseTableViewVC
            let foldButton = tableViewVc?.tableView.tableFooterView?.subviews.first as? UIButton
            if foldButton?.isKind(of: UIButton.self) ?? false {
               foldButton?.isSelected = isFolding ?? false
            }
            tableViewVc?.tableView.reloadData()
        }
    }
    
    init(viewController: LZBaseVC) {
        self.viewController = viewController
    }

    public func injectionIIIAction() {
        
    }
    //折叠tableFooterView点击事件
    open func foldingButtonClick() {
         self.isFolding = !(self.isFolding ?? false)
        
    }
    /// 此方法如果没有分组 就必须要调用返回 1
    ///
    /// - Parameter tableView: UITableView
    /// - Returns: 分组个数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
    }
    
}

/// 模型解析利器
class LZBaseParseJsonTools<T: Mappable>: NSObject {
    public typealias completionBlock = (_ isSuccess: Bool, _ didResult: T?) -> Void
    
    public typealias completionListBlock = (_ isSuccess: Bool, _ didResult: [T]?) -> Void
    
    /// 解析模型
    ///
    /// - Parameters:
    ///   - result: maya返回的
    ///   - completion: 完成的回调
    public static func parsingJson(result: Result<Moya.Response, MoyaError>, completion: @escaping completionBlock ) {
        switch result {
        case let .success(response):
            let jsonStr = try? response.mapJSON()
            if let jsonStr = jsonStr {
                debugPrint(jsonStr  )
            }
             let value = try? response.mapString()
            guard let tempvalue = value else{
                completion(false,nil)
                return
            }
            let baseModel = LZBaseModel<T>(JSONString: tempvalue)
            
            if baseModel?.code != 200 {
                LZHudTool.showMessage(message: baseModel?.msg)
                if baseModel?.code == 9000 {
                    NotificationCenter.default.post(Notification.init(name: LLLoginOutNotification))
                    return
                }
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                    completion(false, nil)
                }
                return
            }
            completion(true, baseModel?.data)
            
            
        case let .failure(error):
            debugPrint(error)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                completion(false, nil)
            }
        }
    }
    
    /// 解析模型数组
    ///
    /// - Parameters:
    ///   - result: maya返回的
    ///   - completion: 完成的回调
    public static func parsingListJson(result: Result<Moya.Response, MoyaError>, completion: @escaping completionListBlock ) {
        switch result {
        case let .success(response):
            let jsonStr = try? response.mapJSON()
            if let jsonStr = jsonStr {
                debugPrint(jsonStr  )
            }
            let value = try? response.mapString()
            guard let tempvalue = value else{
                completion(false,nil)
                return
            }
            let baseModel = LZBaseListModel<T>(JSONString: tempvalue)
            
            if baseModel?.code != 200 {
                LZHudTool.showMessage(message: baseModel?.msg)
                if baseModel?.code == 9000 {
                    NotificationCenter.default.post(Notification.init(name: LLLoginOutNotification))
                    return
                }
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                    completion(false, nil)
                }
                return
            }
            completion(true, baseModel?.data)
            
            
        case let .failure(error):
            debugPrint(error)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                completion(false, nil)
            }
        }
    }
    
   
}


/// 此类适用于 result为 操作成功类的 解析
class LZBaseParseJsonResultTools: NSObject {
    public typealias completionBlock = (_ isSuccess: Bool, _ didResult: LZBaseResultModel?) -> Void
    
    public static func parsingResultJson(result: Result<Moya.Response, MoyaError>, completion: @escaping completionBlock ) {
        switch result {
        case let .success(response):
            let jsonStr = try? response.mapJSON()
            if let jsonStr = jsonStr {
                debugPrint(jsonStr  )
            }
            let value = try? response.mapString()
            guard let tempvalue = value else{
                completion(false,nil)
                return
            }
            let baseModel = LZBaseResultModel(JSONString: tempvalue)
            
            if baseModel?.code != 200 {
                LZHudTool.showMessage(message: baseModel?.msg)
                if baseModel?.code == 9000 {
                    NotificationCenter.default.post(Notification.init(name: LLLoginOutNotification))
                    return
                }
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                    completion(false, nil)
                }
                return
            }
            completion(true,baseModel)
            
            
        case let .failure(error):
            debugPrint(error)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
                completion(false, nil)
            }
        }
    }
    
}
